#include "GTTcpConnection.h"
#include <iostream>
#include <sys/types.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>

GTTcpConnection::GTTcpConnection(const sockaddr_in& stClientSocket, int nNewSock)
:m_stClientSocket(stClientSocket),
m_nSocket(nNewSock)
{
    pthread_t tid;
	pthread_create(&tid, nullptr, &GTTcpConnection::ReceiveThreadFunc, this);

}

GTTcpConnection::~GTTcpConnection()
{

}

void* GTTcpConnection::ReceiveThreadFunc(void* arg)
{
    std::cout << "ReceiveThreadFunc Thread_ID = " << pthread_self() << std::endl;

    GTTcpConnection* pConn = static_cast<GTTcpConnection*>(arg);

    while(1)
    {
        char buf[1024];
        memset(buf, '\0', sizeof(buf));//跟前面的初始化对比
        int nRecvLen = read(pConn->m_nSocket, buf, sizeof(buf));

        /*
        * 注意返回值类型是ssize_t，表示有符号的size_t，这样既可以返回正的字节数、0（表示到达文件末尾）也可以返回负值-1（表示出错）
        */
        if(nRecvLen > 0)
        {
            pConn->NewDataArrived(buf, nRecvLen);

        }
         else if(0 == nRecvLen)
        {
            continue;
            std::cout<< "Received data length = 0" << std::endl;

        } 
        else if(-1 == nRecvLen)
        {
            //TODO exception handle.
        }
         else 
        {

        }
        
    }
}

void GTTcpConnection::NewDataArrived(const char* pData, unsigned int uDataLen)
{
    
}